<template>
  <div class="app-container">
    <el-card shadow="never" class="mb20" :header="form.reportName" style="overflow: visible!important;">
      <el-form label-position="right" label-width="100px">
        <el-row :gutter="10">
          <el-col v-for="(item, index) in queryColumns" :key="index" :span="item.width">
            <el-form-item :label="item.showName">
              <el-input 
              v-if="item.fieldType === Object.keys(columnTypeList)[0]" 
              v-model="item.vModel" 
              :placeholder="`输入${item.showName}`" 
              class="filter-item" 
              :style="{ width: '200px'}"
              />

              <el-input-number 
              v-else-if="item.fieldType === Object.keys(columnTypeList)[1]" 
              v-model="item.vModel" 
              :min="0" 
              class="filter-item" 
              :style="{ width: '150px'}"
              />

              <el-select
              v-else-if="item.fieldType === Object.keys(columnTypeList)[2]"
              v-model="item.vModel"
              class="filter-item"
              clearable
              :style="{ width: '200px'}"
              >
                <el-option v-for="(option, index) in item.options" :key="index" :value="option.key" :label="option.value"></el-option>
              </el-select>

              <el-date-picker
              v-else-if="item.fieldType === Object.keys(columnTypeList)[3]" 
              v-model="item.vModel"  
              type="datetime" 
              clearable
              class="filter-item" 
              :style="{ width: '200px'}"
              :placeholder="`选择${item.showName}`" 
              />

              <DeptSelect
              v-else-if="item.fieldType === Object.keys(columnTypeList)[4]" 
              :clearable="true"
              :selectValue="item.vModel"
              class="filter-item" 
              :style="{ width: '200px'}"
              @select="deptSelect(item, $event)" />

              <DeptPositionS
              v-else-if="item.fieldType === Object.keys(columnTypeList)[5]" 
              :clearable="true"
              :selectValue="item.vModel"
              class="filter-item" 
              :style="{ width: '200px'}"
              @select="deptPositionSelect(item, $event)" />

              <DeptUserS
              v-else-if="item.fieldType === Object.keys(columnTypeList)[6]" 
              :clearable="true"
              :selectValue="item.vModel"
              class="filter-item" 
              :style="{ width: '200px'}"
              @select="deptUserSelect(item, $event)" />
            </el-form-item>
          </el-col>
          <div style="display:inline-block;">
            <el-button class="filter-item" type="primary" icon="el-icon-search" title="点击搜索" @click="handleFilter"></el-button>
            <el-button class="filter-item" type="success" icon="el-icon-download" title="点击导出Excel" @click="handleExport"></el-button>
          </div>
        </el-row>
      </el-form>
    </el-card>
    <el-table
      v-loading="listLoading"
      :data="list"
      element-loading-text="Loading"
      border
      stripe
      fit
      highlight-current-row>
      <el-table-column v-for="(item, index) in reportColumns" :key="index" :label="item.showName" align="center">
      <template slot-scope="scope">
        {{scope.row[item.fieldName]}}
      </template>
      </el-table-column>
    </el-table>
    <pagination v-show="form.pagination == 1 && total>0" :total="total" :page.sync="listQuery.pageNo" :limit.sync="listQuery.pageSize" @pagination="fetchData" />
  </div>
</template>

<script>

import enums from '@/utils/enums'
import moment from 'moment'
import Pagination from '@/views/workflow/components/Pagination'
import DeptSelect from '@/components/DeptSelect'
import DeptPositionS from '@/components/DeptPositionS'
import DeptUserS from '@/components/DeptUserS'
import { calculateValue } from '@/api/workflow/form/index'
import { get, executionQuery, exportReport } from '@/api/report'

export default {
  // name: '报表渲染',
  components: { 
    Pagination,
    DeptSelect,
    DeptPositionS,
    DeptUserS
  },
  data() {
    return {
      queryColumns: [],
      reportColumns: [],
      cols: 0,
      form: {
        reportName: '',
        reportSource: '',
        pagination: 1,
        reportCondition: '',
        reportLayout: ''
      },
      total: 0,
      listQuery: {
        pageNo: 1,
        pageSize: 10
      },
      list: [],
      listLoading: true
    }
  },
  filters: {},
  watch: {
    // queryColumns: {
    //   handler: function(n, o) {
    //   },
    //   deep: true
    // }
  },
  computed: {
    columnTypeList() {
      return enums.COLUMN_TYPE
    },
  },
  async created() {
    await this.getInfo()
    await this.handleFilter()
  },
  methods: {
    async getInfo() { // 获取报表配置信息
      const id = this.$route.query.id
      if (!id) {
        return
      }
      this.form = {}
      const res = await get(id)
      if (res) {
        this.form = res.data
        if (res.data.reportCondition) {
          this.queryColumns = JSON.parse(res.data.reportCondition)
          await this.getSQLOptions()
        }
        if (res.data.reportLayout) {
          this.reportColumns = JSON.parse(res.data.reportLayout)
        }
      }
    },
    async getSQLOptions() { // 
      if (this.queryColumns && this.queryColumns.length) {
        this.queryColumns.forEach(item => {
          if (item.optionValueType) {
            if (item.optionValueType) {
              this.getCalculateValue(item.optionValueType, item.optionValueData, item)
            }
          }
          this.cols+=(item.width ? item.width : 0)
        })
      }
    },
    async getCalculateValue(valueType, valueData, item) { // 获取字段值类型的数据
      const data = {
        valueType: valueType,
        valueData: valueData,
        formData: '{}'
      }
      const res = await calculateValue(data)
      item.options = res.data
    },
    deptSelect(item, callback) {
      item.vModel = callback.value
    },
    deptPositionSelect(item, callback) {
      item.vModel = callback.value
      // 部门岗位组件可能绑定部门、岗位两个字段，查询的时候需要传两个值
      // if (item.deptId) {
      //   item.vModelDeptId = callback.key.split('-')[0]
      // }
      // if (item.positionId) {
      //   item.vModelPositionId = callback.value
      // }
    },
    deptUserSelect(item, callback) {
      item.vModel = callback.value
      // 部门岗位组件可能绑定部门、人员两个字段，查询的时候需要传两个值
      // if (item.deptId) {
      //   item.vModelDeptId = callback.key.split('-')[0]
      // }
      // if (item.userId) {
      //   item.vModelUserId = callback.value
      // }
    },
    handleFilter() {
      this.listQuery.pageNo = 1
      this.fetchData()
    },
    fetchData() { // 获取报表数据
      let params = this.form.pagination == 1 ? JSON.parse(JSON.stringify(this.listQuery)) : {}
      params.reportId = this.form.id
      const condition = this.getConditionParams()
      params.condition = condition
      this.listLoading = true
      executionQuery(params).then(response => {
        this.total = response.data.total
        this.list = response.data.records
        this.listLoading = false
      })
    },
    getConditionParams() { // 获取查询字段的值
      let condition = {}
      this.queryColumns.forEach(item => {
        if (item.vModel) {
          let value = item.vModel
          if (item.fieldType === Object.keys(this.columnTypeList)[3]) {
            value = moment(new Date(item.vModel)).format('YYYY-MM-DD HH:mm:ss')
          }
          if (condition[item.fieldName]) {
            condition[item.fieldName] = condition[item.fieldName] + ',' + value
          } else {
            condition[item.fieldName] = value
          }
        }
        // if (item.fieldType === Object.keys(this.columnTypeList)[5]) {
        //   if (item.deptId) {
        //     condition[item.deptId] = item.vModelDeptId
        //   }
        //   if (item.positionId) {
        //     condition[item.positionId] = item.vModelPositionId
        //   }
        // }
        // if (item.fieldType === Object.keys(this.columnTypeList)[6]) {
        //   if (item.deptId) {
        //     condition[item.deptId] = item.vModelDeptId
        //   }
        //   if (item.userId) {
        //     condition[item.userId] = item.vModelUserId
        //   }
        // }
      })
      return condition
    },
    handleExport() {
      let condition = this.getConditionParams()
      condition = encodeURIComponent(JSON.stringify(condition))
      const paramas = `reportId=${this.form.id}&condition=${condition}`
      const url = `${process.env.VUE_APP_API_BASE_URL}/system/report/export?${paramas}`
      window.open(url, '_blank')
    }
  }
}
</script>
<style lang="scss" scoped>
 .filter-item {
   max-width: 100%;
 }
</style>